package com.briup.server.web.controller;

import com.briup.common.response.Result;
import com.briup.server.domain.dto.KaptchaVerifyRequest;
import com.briup.server.service.KaptchaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@Tag(name = "验证码相关模块")
@RestController
@RequestMapping("/captcha")
@RequiredArgsConstructor
public class CaptchaController {

    private final KaptchaService kaptchaService;

    @GetMapping
    @Operation(summary = "获取验证码")
    @Parameter(name = "formId", description = "表单唯一标识符，用于关联验证码和登录请求")
    public void getCaptcha(HttpServletResponse response, @RequestParam("formId") String formId) throws IOException {
        // 1. 调用service获取验证码图片
        BufferedImage image = kaptchaService.getCaptcha(formId);

        // 2. 设置响应格式为图片
        response.setContentType("image/jpeg");
        // 禁止缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 3. 将图片写入响应流
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "jpg", os);
        os.flush();
        os.close();
    }

    @GetMapping("/sendCode")
    @Operation(summary = "发送验证码邮件")
    public Result<?> sendCode(@RequestParam("email") String email) {
        kaptchaService.sendCode(email);
        return Result.success(null).apply("验证码发送成功");
    }

    @PostMapping("/verify")
    @Operation(summary = "验证验证码（测试时使用）")
    public Result<?> verifyCaptcha(@RequestBody @Valid KaptchaVerifyRequest request) {
        // 1. 调用service验证验证码
        boolean valid = kaptchaService.verifyCaptcha(request);
        // 2. 返回验证结果
        return Result.success(valid)
                .apply("验证码验证成功");
    }
}
